<template>
    <div class="wh-100 overflow-auto" style="background-color: #fff" v-loading="loading">
        <!--头部-->
        <div class="d-flex-between-center fs-14 mt-12 px-20" style="height: 70px; border-bottom: 1px solid #ecf0f6">
            <div class="d-flex-align-center" style="font-size: 16px; font-weight: bold">
                <div :class="activeTab === 1 ? 'tab-cut' : ''" @click="unitCheckIn(1)">学校信息</div>
                <div :class="activeTab === 2 ? 'tab-cut' : ''" class="ml-48" @click="unitCheckIn(2)">院系介绍</div>
            </div>
            <div class="d-flex justify-content-end">
                <!--<Button>返回</Button>-->
            </div>
        </div>
        <div v-if="activeTab === 1" class="mt-12 px-20" style="height: calc(100% - 82px); width: 660px">
            <div class="d-flex-center mt-36 fs-14 mb-36">
                <div class="d-flex-center" style="flex-direction: column">
                    <div>
                        <img style="width: 80px; height: 80px; border-radius: 50%" :src="schoolInformationForm.logo ? schoolInformationForm.logo : ''" />
                        <!--                <template v-else>-->
                        <!--                  <div  style="width:100px;height:100px;border-radius: 50%;background-color:#c0c4cc" ></div>-->
                        <!--                </template>-->
                    </div>
                    <input type="file" id="fileInput" accept=".jpg, .png" style="display: none" @change="handleFileChange" />
                    <div
                        class="fs-12 d-flex-around-center position-relative"
                        style="top: -15px; width: 80px; height: 25px; background-color: #ffffff; border-radius: 2px; border: #2b85e4 1px solid; color: #2b85e4"
                        @click="openFileSelector"
                    >
                        上传学校logo
                    </div>
                    <!--              <Upload class="" action="#" :before-upload="beforeUpload"-->
                    <!--                      ref="upload">-->
                    <!--                <div class="d-flex d-flex-around-center fs-14" style="position:relative;top:-20px;width:90px;height:35px;color: #2d8cf0;border: 1px solid #2d8cf0;background-color:#ffffff;border-radius: 4px">修改</div>-->
                    <!--              </Upload>-->
                    <!--                  <Button type="primary" style="position: relative" >修改</Button>-->
                    <span style="font-size: 12px; color: #909399">点击上传学校标志，像素：200*200排序，格式：jpg，png</span>
                </div>
            </div>
            <Form ref="schoolInformationRef" :model="schoolInformationForm" :rules="schoolInformationRules" :label-width="100">
                <FormItem label="学校代码" prop="code">
                    <Input v-model="schoolInformationForm.code" disabled></Input>
                </FormItem>
                <FormItem label="学校名称" prop="schoolName">
                    <Input v-model="schoolInformationForm.schoolName" disabled></Input>
                </FormItem>
                <div class="d-flex-align-center d-flex-between-center">
                    <FormItem label="学校简称" prop="abbreviation" style="float: left">
                        <Input style="width: 220px" v-model="schoolInformationForm.abbreviation"></Input>
                    </FormItem>
                    <FormItem label="创建年份" prop="createYear">
                        <Input v-model="schoolInformationForm.createYear" disabled style="width: 190px"></Input>
                    </FormItem>
                </div>
                <div class="d-flex-align-center d-flex-between-center">
                    <FormItem label="学校类型" prop="nature">
                        <Select v-model="schoolInformationForm.nature" style="width: 220px">
                            <Option value="理工院校">理工类</Option>
                            <Option value="综合院校">综合类</Option>
                            <Option value="财金院校">财金类</Option>
                            <Option value="师范院校">师范类</Option>
                            <Option value="农林院校">农林类</Option>
                            <Option value="政法院校">政法类</Option>
                            <Option value="医药院校">医药类</Option>
                            <Option value="民族院校">民族类</Option>
                            <Option value="语言院校">语言类</Option>
                            <Option value="艺术院校">艺术类</Option>
                            <Option value="体育院校">体育类</Option>
                            <Option value="军事院校">军事类</Option>
                            <Option value="旅游院校">旅游类</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="学校性质" prop="type">
                        <Select v-model="schoolInformationForm.type" style="width: 190px">
                            <Option value="大学">公立大学</Option>
                            <Option value="民办大学">民办大学</Option>
                        </Select>
                    </FormItem>
                </div>
                <FormItem label="联系邮箱" prop="schoolEmail">
                    <Input v-model="schoolInformationForm.schoolEmail" placeholder="填写学校邮箱"></Input>
                </FormItem>
                <FormItem label="所在城市" prop="city">
                    <div class="d-flex-align-center">
                        <el-select no-match-text="暂无数据"   style="width: 200px" v-model="schoolInformationForm.location" @change="selectTrigger" filterable no-data-text="暂无数据">
                            <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item.name" no-data-text="暂无数据"></el-option>
                        </el-select>
                        <el-select
                            style="width: 200px"
                            v-model="schoolInformationForm.locationCity"
                            filterable
                            :remote="true"
                            :remote-method="加载中"
                            no-match-text="暂无数据"  no-data-text="暂无数据"
                            @change="selectTriggerA"
                            @visible-change="visibleChangeA"
                        >
                            <el-option filterable="true" v-for="item in cityList" :key="item.id" :label="item.name" :value="item.name"></el-option>
                        </el-select>
                        <el-select
                            style="width: 200px"
                            v-model="schoolInformationForm.locationArea"
                            filterable
                            :remote="true"
                            :remote-method="加载中"
                            no-match-text="暂无数据"  no-data-text="暂无数据"
                            @visible-change="visibleChangeB"
                        >
                            <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.name" no-data-text="暂无数据"></el-option>
                        </el-select>
                    </div>
                </FormItem>
                <FormItem label="详细地址" prop="locationDetail">
                    <Input v-model="schoolInformationForm.locationDetail" placeholder="填写学校详细地址"></Input>
                </FormItem>
                <FormItem label="标签" prop="schoolLabel">
                    <Input v-model="schoolInformationForm.schoolLabel" placeholder="填写学校标签，逗号分隔 如 双一流，211"></Input>
                </FormItem>
                <FormItem label="学校简介" prop="schoolBrief">
                    <Input type="textarea" :rows="10" v-model="schoolInformationForm.schoolBrief" :maxlength="3000" placeholder="介绍自己的学校，最多3000字"></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="submitSchoolForm" :loading="schoolButton">提交</Button>
                </FormItem>
            </Form>
        </div>
        <!--院系信息-->
        <div v-if="activeTab === 2" class="w-100 overflow-auto px-20 d-flex-center" style="height: calc(100% - 62px)">
            <!--左侧🌲-->
            <div class="mt-12 fs-16" style="width: 300px; height: 100%">
                <dl>
                    <dt @click="getCollegesList(school.gxcode)" class="py-12 d-flex">
                        <Icon v-if="isShow" size="12" type="ios-arrow-down" />
                        <Icon v-else size="12" type="ios-arrow-forward" />
                        <Icon style="margin-left: 5px; margin-right: 5px" size="12" type="ios-home-outline" />
                        {{ school.gxmc }}
                    </dt>
                    <dd class="ml-24 py-12 d-flex" :class="isactive == index ? 'selected' : ''" v-for="(item, index) in collegesList" @click="getCheckID(item.id, index)">
                        <Icon class="ml-12" size="12" style="margin-right: 5px" type="ios-school-outline" />
                        {{ item.yxname }}
                    </dd>
                </dl>
                <!--              <el-tree-->
                <!--                  :data="treeData"-->
                <!--                  :props="defaultProps"-->
                <!--                  :load="loadNode"-->
                <!--                  :lazy="true"-->
                <!--                  @node-click="handleNodeClick">-->
                <!--              </el-tree>-->
                <!--              <el-tree-->
                <!--                  :data="treeData"-->
                <!--                  :props="defaultProps"-->
                <!--                  node-key="id"-->
                <!--                  :load="loadNode"-->
                <!--                  @node-click="getCheckID">-->
                <!--                <div slot-scope="{node,data}">-->
                <!--                  <Icon class="" size="20px" style="margin-right: 5px" v-if="data.children" type="ios-home-outline" />-->
                <!--                  <Icon v-else style="margin-right: 5px" type="ios-school-outline" />-->
                <!--                  <span :class="schoolid === data.id ? 'select-tree' : ''">{{ node.label}}</span>-->
                <!--                </div>-->

                <!--              </el-tree>-->
            </div>
            <!--右侧表单-->
            <div class="flex-1 mt-20 fs-14 h-100">
                <Form ref="facultyRef" :model="facultyForm" :rules="facultyRules" :label-width="100">
                    <FormItem style="width: 400px" label="学院名称" prop="collegeName">
                        <Input disabled v-model="facultyForm.yxname"></Input>
                    </FormItem>
                    <FormItem style="width: 400px" label="联系电话" prop="collegePhone">
                        <Input v-model="facultyForm.collegePhone"></Input>
                    </FormItem>
                    <FormItem style="width: 400px" label="标签" prop="collegeLable">
                        <Input v-model="facultyForm.collegeLabel" placeholder="填写学校标签，逗号分隔 如 双一流，211"></Input>
                    </FormItem>
                    <FormItem style="width: 500px" label="院系介绍" prop="collegeBrief">
                        <Input type="textarea" :rows="7" v-model="facultyForm.collegeBrief" placeholder="学院简介，最多1000字"></Input>
                    </FormItem>
                    <FormItem label="" prop="">
                        <Button style="width: 100px" type="primary" @click="submitDepartmentForm" :loading="departmentButton">提交</Button>
                    </FormItem>
                </Form>
            </div>
        </div>
    </div>
</template>

<script>
import {
    getAllSchoolInfoAPI,
    getCollageInfoByIdAPI,
    getCurrentSchoolInfoAPI,
    getListByCodeAPI,
    getParentCollageAPI,
    updateAllSchoolInfoAPI,
    updateCollegeAPI
} from '../../../api/bys/siteAdministration/index';
import { getAreaAPI, getCityAPI, getProvinceAPI, imageUploadDataApi } from '../../../api/bys/index';
// region TODO 上传的图片头像
let selectedFile = null;
// region TODO tab切换
const activeTab = 1;
// endregion

// region TODO 学校信息Form
const schoolInformationForm = {};
const logo = '';
const schoolInformationRules = {
    schoolEmail: [
        {
            validator: function (rule, value, callback) {
                if (/^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(value) == false) {
                    callback(new Error('邮箱格式错误'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
};
const imgSrc = '';
const formFile = null;
const formData = new FormData();
// endregion

// region TODO 院校信息
// region TODO 🌲
const schoolid = '';
// endregion

// region TODO 表单
const facultyForm = {};
const facultyRules = {};
// endregion
// endregion
export default {
    data() {
        return {
            isactive: '',
            loading: false,
            schoolButton: false,
            departmentButton: false,
            provinceList: [],
            collegesListA: [],
            cityList: [],
            areaList: [],
            treeData: [],
            isShow: false,
            defaultProps: {
                children: 'children',
                label: 'gxmc',
                id: 'gxcode'
            },
            school: {},
            collegesList: [],
            formData,
            logo,
            schoolid,
            facultyForm,
            facultyRules,
            activeTab,
            formFile,
            imgSrc,
            schoolInformationForm,
            schoolInformationRules
        };
    },
    created() {
        this.getSchoolInformation();
        this.initSchoolData();
        // this.getAcademyInformation()
        this.getProvince();
    },
    mounted() {},
    methods: {
        async initSchoolData() {
            const resA = await getCurrentSchoolInfoAPI();
            this.school = resA?.result || {};
            if (resA.success) {
                let code = resA.result.gxcode;
                const resB = await getListByCodeAPI({ schoolCode: code });
                this.collegesListA = resB?.result || [];
            }
        },
        getCollegesList(code) {
            this.isShow = !this.isShow;
            if (this.isShow) {
                this.collegesList = this.collegesListA;
                this.isactive = '';
            } else {
                this.collegesList = [];
                this.isactive = '';
            }
            // this.collegesList = this.collegesListA
            // getListByCodeAPI({schoolCode:code}).then(res => {
            //   console.log(res,'院系信息')
            //   if (this.isShow){
            //     this.collegesList = res.result
            //     this.isactive = ''
            //   }else{
            //     this.collegesList = []
            //     this.isactive = ''
            //   }
            //   // this.collegesList = res?.result || []
            // })
        },
        loadNode(node, resolve) {
            console.log(node.level, 'node.level');
            if (node.level === 1) {
                getListByCodeAPI(node.data.gxcode).then(data => {
                    // 假设 data 是院系列表的数组
                    const children = data.map(item => ({ gxmc: item.yxname, gxcode: item.id }));
                    resolve(children);
                });
            } else {
                //没有更多子节点
                resolve([]);
            }
        },
        // region TODO 省市数据
        async getProvince() {
            await getProvinceAPI().then(res => {
                console.log(res, '省级');
                this.provinceList = res.result;
            });
        },
        visibleChangeA(e) {
            if (e) {
                console.log(e);
                this.getCity();
            }
        },
        visibleChangeB(e) {
            if (e) {
                console.log(e);
                this.getArea();
            }
        },
        selectTrigger() {
            this.issueForm.locationCity = '';
            this.getCity();
        },
        async getCity() {
            var newData = this.provinceList.filter(item => item.name === this.schoolInformationForm.location); //返回对象
            console.log(newData);
            let response = await getCityAPI({ provinceId: newData[0].id });
            if (response.success) {
                this.cityList = response?.result || [];
                console.log(this.cityList, '市级');
            }
        },
        selectTriggerA() {
            this.issueForm.locationArea = '';
            this.getArea();
        },
        async getArea() {
            debugger;
            var newData = this.cityList.filter(item => item.name === this.schoolInformationForm.locationCity); //返回对象
            console.log(newData);
            await getAreaAPI({
                cityId: newData[0].id
            }).then(res => {
                console.log(res, '区级');
                this.areaList = res.result;
                console.log(this.areaList, '区级');
            });
        },
        async getSchoolInformation() {
            this.loading = true;
            let response = await getAllSchoolInfoAPI();
            if (response.success) {
                this.schoolInformationForm = response?.result || [];
                this.loading = false;
            }
        },

        getAcademyInformation() {
            this.loading = true;
            getCurrentSchoolInfoAPI().then(res => {
                console.log(res);
                this.treeData = [res?.result || {}];
                this.loading = false;
            });
        },
        getCheckID(id, index) {
            this.isactive = index;
            getCollageInfoByIdAPI({ id: id }).then(res => {
                console.log(res, '详细信息');
                this.facultyForm = res.result;
            });
            // this.treeData.forEach(item=>{
            //   if (item.id !== data.id){
            //     this.$nextTick(()=>{
            //       this.facultyForm = data
            //       this.facultyForm.collegeLable = data.collegeLable
            //     })
            //   }
            // })
        },
        unitCheckIn(data) {
            this.activeTab = data;
        },
        async beforeUpload(file) {
            this.formData.append('file', file);
            this.logo = URL.createObjectURL(file);
            const uploadResponse = await imageUploadDataApi(this.formData);
            if (uploadResponse.code == 200) {
                console.log('文件地址', uploadResponse);
                this.schoolInformationForm.logo = uploadResponse.result;
            }
            console.log(this.formData.get('file'), '234');
        },
        // region TODO 提交学校表单
        submitSchoolForm() {
            this.schoolButton = true;
            //调接口
            updateAllSchoolInfoAPI(this.schoolInformationForm)
                .then(res => {
                    if (res.success) {
                        this.$message.success('修改成功！');
                        this.schoolButton = false;
                    } else {
                        this.schoolButton = false;
                    }
                })
                .catch(err => {
                    this.schoolButton = false;
                });
        },

        // submitSchoolForm() {
        //   this.schoolButton = true
        //   console.log(this.formData)
        //   //调接口
        //     this.postRequest("/upload/file",this.formData,{
        //       transformRequest:[]
        //     }).then(res => {
        //
        //       //头像上传成功
        //       if(res.success) {
        //         this.schoolInformationForm.logo = res.result
        //
        //         //调接口
        //         updateAllSchoolInfoAPI(this.schoolInformationForm).then((res) => {
        //           if (res.success){
        //             this.schoolButton = false
        //           }else{
        //             this.schoolButton = false
        //           }
        //         }).catch(err => {
        //           console.log(err)
        //           this.schoolButton = false
        //         })
        //       }
        //     })
        // },
        // endregion
        openFileSelector() {
            document.getElementById('fileInput').click();
        },
        async handleFileChange(event) {
            console.log(111111111);
            selectedFile = event.target.files[0];
            this.formData.append('file', selectedFile);
            this.schoolInformationForm.logo = URL.createObjectURL(selectedFile);
            const uploadResponse = await imageUploadDataApi(this.formData);
            if (uploadResponse.code == 200) {
                console.log('文件地址', uploadResponse);
                this.schoolInformationForm.logo = uploadResponse.result;
                this.submitSchoolForm();
                console.log(this.schoolInformationForm.logo, 'logo');
            }
            // console.log(this.formData.get('file'), '234')
            // console.log(selectedFile, 'selectedFile')
            // this.schoolInformationForm.logo = URL.createObjectURL(selectedFile);
            // console.log(this.schoolInformationForm.logo, 'logo')
        },
        // region TODO 提交学院表单
        submitDepartmentForm() {
            this.departmentButton = true;

            updateCollegeAPI(this.facultyForm)
                .then(res => {
                    if (res.success) {
                        this.$message.success('修改成功');
                        this.departmentButton = false;
                    } else {
                        this.$message.error('');
                        this.departmentButton = false;
                    }
                })
                .catch(err => {
                    this.departmentButton = false;
                });
        }
        // endregion
    }
};
</script>

<style scoped lang="less">
.tab-cut {
    color: #0094fa;
    height: 50px;
    line-height: 50px;
    border-bottom: 3px solid #0094fa;
}
.select-tree {
    color: #1d8ce0;
}
.button-style {
    top: -10px;
    width: 80px;
    height: 30px;
    background-color: #ffffff;
    border-radius: 5px;
    border: #0f83f9 1px solid;
    color: #0f83f9;
}
#listStyle {
    background: linear-gradient(90deg, #d7e7fc, #fff);
}
.selected {
    color: #1684e9;
    background: linear-gradient(90deg, #d7e7fc, #fff);
}
</style>
